package cn.chinaiptv.user;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Properties;

import org.apache.log4j.Logger;

public class UserReaderWriter {

	/**
	 * 根据主键key读取主键的值value
	 * 
	 * @param key
	 *            键名
	 */
	public String readUserPassword(String key) {
		InputStream in = null;
		Properties propsIn = new Properties();
		ClassLoader cl = UserReaderWriter.class.getClassLoader();
		URL url = cl.getResource("users.properties");
		System.out.println("url：" + url);
		String path = url.getPath();
		Logger logger = Logger.getLogger(UserReaderWriter.class);
		logger.info("------------------" + path);

		try {

			in = new BufferedInputStream(new FileInputStream(path));
			propsIn.load(in);
			String value = propsIn.getProperty(key);
			System.out.println(key + "键的值是：" + value);
			propsIn = null;
			return value;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 更新（或插入）一对properties信息(主键及其键值) 如果该主键已经存在，更新该主键的值； 如果该主键不存在，则插件一对键值。
	 * 
	 * @param keyname
	 *            键名
	 * @param keyvalue
	 *            键值
	 */

	public boolean writeProperties(String keyname, String keyvalue) {
		ClassLoader cl = UserReaderWriter.class.getClassLoader();
		URL url = cl.getResource("users.properties");
		System.out.println("url：" + url);
		String path = url.getPath();
		Properties propsOut = new Properties();
		OutputStream out = null;
		boolean result = false;
		try {

			InputStream in = new BufferedInputStream(new FileInputStream(path));
			propsOut.load(in);
			in.close();
			out = new FileOutputStream(path);
			propsOut.setProperty(keyname, keyvalue);
			// 以适合使用 load 方法加载到 Properties 表中的格式，
			// 将此 Properties 表中的属性列表（键和元素对）写入输出流
			propsOut.store(out, null);
			propsOut = null;
			result = true;
		} catch (IOException e) {
			System.err.println("属性文件更新错误");
		} finally {

			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}

}
